import React, { useEffect, useLayoutEffect, useState } from 'react';
import {
  Text,
  ScrollView,
  publishDps,
  exitMiniProgram,
  hideMenuButton,
  vibrateShort,
  getSystemInfoSync,
  navigateTo,
  showToast,
  router,
  getLaunchOptionsSync,
  queryDps,
  useAppEvent,
} from '@ray-js/ray';
import clsx from 'clsx';

import {
  useDevice,
  useActions,
  useProps,
  useStructuredActions,
  useStructuredProps,
} from '@ray-js/panel-sdk';
import { getCachedSystemInfo } from '@/api/getCachedSystemInfo';
import Strings from '@/i18n';
import { ConfigProvider, NavBar, Battery, Icon, DialogInstance, Dialog } from '@ray-js/smart-ui';
import _ from 'lodash';
import ColorPic from '@/components/ColorPic';
import {
  rgb2hsv,
  hsv2rgbString,
  kelvin2rgb,
  hex2hsv,
  brightKelvin2rgb,
} from '@ray-js/panel-sdk/lib/utils/color';

// import moment from 'moment';
import {
  Image,
  View,
  Switch,
  BottomBar,
  ColorSet,
  SongSet,
  ContolBox,
  AlarmList,
  TimeModeSet,
  CountDownPicker,
  TimeRemainer,
} from '@/components';
import { useThrottleFn } from 'ahooks';
import useGetNewAddCode from '@/hooks/useGetNewAddCode';
import { allList, getCurrentByIndex } from '@/components/SongSet/index';
import { LogoComponent } from '@/components/logoComponent';

import styles from './index.module.less';
import noiceRes from '../../../public/noiceImage';
import { decodeTime, generateCurrentTime } from './time';

const { safeArea } = getCachedSystemInfo();

const { height } = safeArea;

export function Home() {
  const deviceName = useDevice(d => d.devInfo.name);
  const deviceId = useDevice(d => d.devInfo.devId);
  const groupId = useDevice(d => d.devInfo.groupId);

  const isZh = Strings.__language === 'zh';

  // const data = useStaticsRange({
  //   range: 'month',
  //   dpId: 8,
  //   deviceId,
  //   type: 'avg',
  //   date: Date.now(),
  //   code: 'excretion_time_day',
  // });
  // console.log(`🚀 ~ data:`, data);

  // return <View>12312312</View>;

  const {
    switch_music: switchMusic,
    music_list = '1',
    battery_percentage: batteryPercentage,
    child_lock: childLock,
    show_clock: showClock,

    time_mode: timeMode,
    charge_state: chargeState,
    clock_done: clockDone,
    countdown,
    bluetooth_control: bluetoothControl,
  } = useProps(props => props);

  const [localTime, setLocalTime] = useState(generateCurrentTime());

  // 1419${month}${day}${hours}${minutes}`
  const timeInfo = decodeTime(localTime, timeMode);

  const musicList = +music_list;

  const currentInfo = getCurrentByIndex(musicList);

  const [tab, setTab] = useState<'home' | 'time' | 'alarm' | 'sound'>('home');

  useEffect(() => {
    if (tab === 'time') {
      setLocalTime(generateCurrentTime());
    }

    const interval = setInterval(() => {
      if (tab === 'time') {
        const currentTimeStr = generateCurrentTime();
        setLocalTime(currentTimeStr);
      }
    }, 1000);

    return () => {
      clearInterval(interval);
    };
  }, [tab]);

  const [currentCD, setCurrentCD] = useState(countdown);

  const [scrollEnabled, setScrollEnabled] = useState(false);

  const dpStructuredActions = useStructuredActions();
  const colour = useStructuredProps(props => props.colour_data);

  useLayoutEffect(() => {
    hideMenuButton();
  }, []);

  const open = () => {
    DialogInstance.confirm({
      selector: '#smart-dialog2',
      title: Strings.getLang('clock'),
      confirmButtonText: Strings.getLang('close'),
      cancelButtonText: Strings.getLang('waitMinute'),
      confirmButtonColor: '#FF4D4F',
      cancelButtonColor: '#000',
    })
      .then(() => {
        publishDps({
          snooze: true,
          clock_done: false,
        });
      })
      .catch(() => {
        publishDps({
          stop: true,
          clock_done: false,
        });
      });
  };

  useEffect(() => {
    if (clockDone) {
      open();
    }
  }, [clockDone]);

  const volumeSet = useProps(props => +props.volume_set);

  const lightMode = useProps(props => props.light_mode);
  const brightValue = useProps(props => props.bright_value);

  const colourCycle = useProps(props => props.colour_cycle);

  useAppEvent('onShow', () => {
    const {
      query: { deviceId },
    } = getLaunchOptionsSync();

    queryDps({
      deviceId,
      dpIds: ['107', '104', '105'],
      success: res => {
        console.log('queryDps success', res);
      },
      fail: error => {
        console.log('queryDps fail', error);
      },
    });
  });

  const setCollorCycle = (val: boolean) => {
    vibrateShort({ type: 'light' });
    publishDps({
      colour_cycle: val,
    });
  };

  const setTimeMode = (val: '12h' | '24h') => {
    vibrateShort({ type: 'light' });
    publishDps({
      time_mode: val,
    });
  };

  const setShowClock = (val: boolean) => {
    vibrateShort({ type: 'light' });
    publishDps({
      show_clock: val,
    });
  };

  const setChildLock = (val: boolean) => {
    vibrateShort({ type: 'light' });
    publishDps({
      child_lock: val,
    });
  };

  const onClickLeft = () => {
    exitMiniProgram();
  };

  const getBatNumber = (v: number) => {
    if (v === 0) return 0;

    if (v < 34) return 1;
    if (v < 67) return 2;

    return 3;
  };

  const newAddCode = useGetNewAddCode();

  const handleJump = useThrottleFn(
    (code: string) => {
      router.push(`/${code}`);
    },
    { wait: 80 }
  ).run;

  const renderHeader = (title, showAddAlarmBtn = false) => {
    return (
      <View className={styles.header}>
        <Text className={styles.devName}>{title}</Text>
        {showAddAlarmBtn ? (
          <View
            className={styles.addAlarmBox}
            onClick={() => {
              handleJump(`clockEdit?code=${newAddCode}&enabledDelete=${false}`);
            }}
          >
            <Image src={noiceRes.add_alarm} className={styles.addAlarmIcon} />
            <Text>{Strings.getLang('addAlarms')}</Text>
          </View>
        ) : (
          <View className={styles.batteryBoxContainer}>
            <View className={clsx(styles.batteryBox, { [styles.batteryBoxCharge]: chargeState })}>
              <Image
                src={
                  batteryPercentage < 15
                    ? noiceRes.batempty
                    : noiceRes[`b_${getBatNumber(batteryPercentage)}`]
                }
                className={styles.emptyContainer}
              />
            </View>

            {tab === 'home' ? (
              <Image
                src={noiceRes.tips}
                className={styles.tips}
                onClick={() => {
                  showToast({
                    icon: 'none',
                    title: `todo 跳转到产品说明 等待图片`,
                  });
                }}
              />
            ) : null}
          </View>
        )}
      </View>
    );
  };

  const color = hsv2rgbString(
    lightMode === 'white' ? 56 : colour.hue,
    lightMode === 'white' ? Math.floor(brightValue / 33) : colour.value / 10,
    Math.floor(100)
  );

  const renderHome = () => {
    return (
      <View className={styles.homeBox}>
        {renderHeader(Strings.getLang('homeTitle'))}
        <View className={styles.switchContainer}>
          <View className={styles.switchBox}>
            <Text className={styles.switchText}>{Strings.getLang('colourCycle')}</Text>
            <Switch value={colourCycle} onValueChange={v => setCollorCycle(v)} />
          </View>
          <View className={styles.switchBox}>
            <Text className={styles.switchText}>{Strings.getLang('showClock')}</Text>
            <Switch value={showClock} onValueChange={v => setShowClock(v)} />
          </View>
          <View className={styles.switchBox}>
            <Text className={styles.switchText}>{Strings.getLang('childLock')}</Text>
            <Switch value={childLock} onValueChange={v => setChildLock(v)} />
          </View>

          {/* <View className={styles.bigLog}>
            <Image src={noiceRes.logoContainer} className={styles.imgContainer} />
            <ColorPic color={color} className={styles.canvas} />
          </View> */}
          <LogoComponent color={color} scale={1.7} />
        </View>
        <ColorSet
          colour={{
            ...colour,
            value: lightMode === 'white' ? brightValue : colour.value,
          }}
          onChange={val => {
            if (lightMode === 'white') {
              publishDps({
                bright_value: val.value,
              });
            } else {
              dpStructuredActions.colour_data.set(val);
            }
          }}
          onHueChange={val => {
            dpStructuredActions.colour_data.set({
              ...colour,
              hue: val,
            });
          }}
          onHueStart={() => {
            if (lightMode == 'white') {
              publishDps({
                light_mode: 'color',
              });
            }
          }}
          voice={volumeSet}
          changeVoice={v => {
            publishDps({
              volume_set: v,
            });
          }}
        />

        <View className={styles.controlBox}>
          <View className={styles.songInfo}>
            <Image
              src={bluetoothControl ? noiceRes.ble_b : currentInfo?.imageActive}
              className={styles.songImage}
            />
            <Text className={styles.title}>
              {bluetoothControl ? Strings.getLang('bluetooth') : currentInfo?.name}
            </Text>
          </View>

          <View className={styles.controlBoxItemWrap}>
            <Image
              src={noiceRes.prev}
              className={styles.controlBoxItem}
              onTap={() => {
                vibrateShort({ type: 'middle' });
                if (bluetoothControl) {
                  publishDps({
                    music_control: 'up',
                  });
                  return;
                }
                publishDps({
                  music_list:
                    musicList - 1 > 0 ? (musicList - 1).toString() : allList.length.toString(),
                });
              }}
            />

            <View
              className={styles.controlBoxCenter}
              onTap={() => {
                // setScrollEnabled(false);

                vibrateShort({ type: 'middle' });
                publishDps({
                  switch_music: !switchMusic,
                });
              }}
            >
              <Image
                src={switchMusic ? noiceRes.stop : noiceRes.play}
                className={clsx(styles.controlBoxItem, !switchMusic && styles.play)}
              />
            </View>

            <Image
              src={noiceRes.next}
              className={styles.controlBoxItem}
              onTap={() => {
                // setScrollEnabled(false);

                vibrateShort({ type: 'middle' });
                if (bluetoothControl) {
                  publishDps({
                    music_control: 'down',
                  });
                  return;
                }
                publishDps({
                  music_list: ((musicList % allList.length) + 1).toString(),
                });
              }}
            />
          </View>
        </View>
      </View>
    );
  };

  const renderSound = () => {
    return (
      <View className={styles.soundBox}>
        {renderHeader(Strings.getLang('soundTitle'))}
        <ContolBox
          current={musicList}
          switchMusic={switchMusic}
          voice={volumeSet}
          isBle={bluetoothControl}
          color={color}
          changeVoice={v => {
            publishDps({
              volume_set: v,
            });
          }}
          onSongeChange={v => {
            publishDps({
              music_list: v.toString(),
            });
          }}
          onStatusChange={v => {
            publishDps({
              switch_music: v,
            });
          }}
          className={styles.controlBoxSound}
        />
        <SongSet
          current={musicList}
          onSongeChange={v => {
            const params: any = {
              music_list: v.toString(),
            };
            if (bluetoothControl) {
              // ts-ignore
              params.bluetooth_control = false;
            }
            publishDps(params);
          }}
        />
      </View>
    );
  };

  const renderTime = () => {
    return (
      <View className={styles.timeBox}>
        {renderHeader(Strings.getLang('timeTitle'))}

        <View>
          <Text className={clsx(styles.timeText1, styles.textBold)}>
            {isZh
              ? `${timeInfo.monthStr},  ${timeInfo.dayStr} ${timeInfo.year}`
              : `${timeInfo.year}-${timeInfo.month}-${timeInfo.day}`}
          </Text>
          <View>
            <Text className={styles.timeText1}>{timeInfo.weekStr}</Text>
          </View>
          <View>
            <Text className={styles.timeText2}>
              {timeInfo.hourStr}:{timeInfo.minute}
            </Text>
            <Text className={styles.timeText3}>{timeInfo.ampmStr}</Text>
          </View>
        </View>

        <View className={styles.PickerBox}>
          <CountDownPicker current={currentCD} setCurrentCD={setCurrentCD} />
        </View>

        <TimeModeSet value={timeMode} changeValue={v => setTimeMode(v)} />

        <View
          className={styles.saveBtn}
          onClick={() => {
            publishDps({
              countdown: currentCD,
            });
          }}
        >
          <Text>{Strings.getLang('confirm')}</Text>
        </View>

        {countdown !== 0 ? <TimeRemainer value={countdown} /> : null}
      </View>
    );
  };

  const renderAlarms = () => {
    return (
      <View className={styles.alarmsBox}>
        {renderHeader(Strings.getLang('alarmsTitle'), !!newAddCode)}
        <AlarmList />
      </View>
    );
  };

  return (
    <View className={styles.view}>
      <NavBar
        title={Strings.getLang('deviceName')}
        className={styles.navBar}
        leftArrow
        onClickLeft={onClickLeft}
        slot={{
          right: (
            <View className={styles.tabTopIconWrap}>
              <Image
                onClick={() => {
                  const jumpUrl = `functional://settings/detail?deviceId=${deviceId ||
                    ''}&groupId=${groupId || ''}`;
                  navigateTo({
                    url: jumpUrl,
                  });
                }}
                src={noiceRes.dot}
              />
            </View>
          ),
        }}
        customClass={styles.borBot}
      />
      <ScrollView
        scrollY={scrollEnabled}
        refresherTriggered
        className={clsx(styles.slideUpContent)}
        style={{
          height: `calc(${height}px - 100px)`,
        }}
      >
        {tab === 'home' ? renderHome() : null}
        {tab === 'sound' ? renderSound() : null}
        {tab === 'time' ? renderTime() : null}
        {tab === 'alarm' ? renderAlarms() : null}
      </ScrollView>
      <BottomBar active={tab} onChange={setTab} />
      <ConfigProvider
        themeVars={{
          bottomSheetMinHeight: '400',
        }}
      >
        <Dialog id="smart-dialog2" />
      </ConfigProvider>
    </View>
  );
}

export default Home;
